/**
 * 图片拼接工具
 */

/**
 * 将多张图片拼接成一张图片
 * @param {Array<string>} imageUrls - 图片URL数组
 * @param {Object} options - 配置选项
 * @param {number} options.width - 输出图片宽度，默认512
 * @param {number} options.height - 每个图片的高度，默认512
 * @param {number} options.spacing - 图片间距，默认10
 * @param {string} options.direction - 拼接方向，'horizontal'横向 或 'vertical'纵向，默认横向
 * @returns {Promise<string>} 返回blob URL
 */
export function mergeImages(imageUrls, options = {}) {
  return new Promise((resolve, reject) => {
    const {
      width = 512,
      height = 512,
      spacing = 10,
      direction = 'horizontal'
    } = options

    if (!imageUrls || imageUrls.length === 0) {
      reject(new Error('图片数组不能为空'))
      return
    }

    // 过滤掉无效的URL
    const validUrls = imageUrls.filter(url => url && url.trim())
    if (validUrls.length === 0) {
      reject(new Error('没有有效的图片URL'))
      return
    }

    // 创建canvas
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    // 计算canvas尺寸
    if (direction === 'horizontal') {
      // 横向拼接
      canvas.width = width * validUrls.length + spacing * (validUrls.length - 1)
      canvas.height = height
    } else {
      // 纵向拼接
      canvas.width = width
      canvas.height = height * validUrls.length + spacing * (validUrls.length - 1)
    }

    // 加载所有图片
    const imagePromises = validUrls.map((url, index) => {
      return new Promise((imgResolve, imgReject) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'

        img.onload = () => {
          imgResolve({
            image: img,
            index: index
          })
        }

        img.onerror = () => {
          console.warn(`Failed to load image: ${url}`)
          imgReject(new Error(`Failed to load image: ${url}`))
        }

        img.src = url
      })
    })

    Promise.all(imagePromises)
      .then(imageData => {
        // 按index排序
        imageData.sort((a, b) => a.index - b.index)

        // 绘制图片
        imageData.forEach((item, index) => {
          let x = 0
          let y = 0

          if (direction === 'horizontal') {
            x = index * (width + spacing)
            y = 0
          } else {
            x = 0
            y = index * (height + spacing)
          }

          // 绘制白色背景
          ctx.fillStyle = '#FFFFFF'
          ctx.fillRect(x, y, width, height)

          // 居中绘制图片（保持宽高比）
          const img = item.image
          const imgAspect = img.width / img.height
          const targetAspect = width / height

          let drawWidth = width
          let drawHeight = height
          let drawX = x
          let drawY = y

          if (imgAspect > targetAspect) {
            // 图片更宽，以宽度为准
            drawHeight = width / imgAspect
            drawY = y + (height - drawHeight) / 2
          } else {
            // 图片更高，以高度为准
            drawWidth = height * imgAspect
            drawX = x + (width - drawWidth) / 2
          }

          ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight)
        })

        // 转换为blob
        canvas.toBlob(
          blob => {
            if (blob) {
              const blobUrl = URL.createObjectURL(blob)
              resolve(blobUrl)
            } else {
              reject(new Error('Canvas转换blob失败'))
            }
          },
          'image/png',
          1.0
        )
      })
      .catch(error => {
        reject(error)
      })
  })
}

/**
 * 将blob URL转换为base64
 * @param {string} blobUrl - blob URL
 * @returns {Promise<string>} base64字符串
 */
export function blobToBase64(blobUrl) {
  return new Promise((resolve, reject) => {
    fetch(blobUrl)
      .then(response => response.blob())
      .then(blob => {
        const reader = new FileReader()
        reader.onloadend = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsDataURL(blob)
      })
      .catch(reject)
  })
}


